package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 实现用户登录
 * 程序启动后要求用户输入用户名和密码,
 * 与userinfo中的记录匹配则登录成功, 否则登录失败
 */
public class UserLogin {
    public static void main(String[] args) {
        /*
            SELECT username,password
            FROM userinfo
            WHERE username='' AND password='';

            如果输入:
            用户名:jsdfkjs(随意输入)
            密码:a' OR '1'='1
            此时sql的语义就发生了变化, 变成了以下语句:
            WHERE username='' AND password='a' OR '1'='1'
            这个条件一定为true, 这种情况称为SQL注入攻击
         */
        UserInfo userInfo = InputUtil.getInputObject(new UserInfo(), "欢迎登录", "login");
        try (
                Connection connection = DBUtil.getConnection();
                ){
//            System.out.println("数据库连接成功");
            Statement statement = connection.createStatement();
            String sql = "SELECT username,password\n" +
                         "FROM userinfo\n" +
                         "WHERE username='"+userInfo.getUsername()+"' AND password='"+userInfo.getPassword()+"';";
            ResultSet rs = statement.executeQuery(sql);
            if (rs.next())
                System.out.println("登录成功");
            else
                System.out.println("登陆失败, 用户名或密码错误");

        } catch (SQLException e) {
            e.printStackTrace();
        }



    }
}
